package com.ebc.eservice.service.app.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ebc.eservice.mapper.*;
import com.ebc.eservice.pojo.*;
import com.ebc.eservice.pojo.pic.UploadFile;
import com.ebc.eservice.service.app.PersonCardService;
import com.ebc.eservice.util.JsonResult;
import com.ebc.eservice.util.MyTimeUtil;
import com.ebc.eservice.vo.card.CardInfoVo;
import com.ebc.eservice.vo.card.CardStatReqVo;
import com.ebc.eservice.vo.card.Message.CardMessageListVo;
import com.ebc.eservice.vo.card.Message.CardMessageReqVo;
import com.ebc.eservice.vo.card.Message.CardMessageRespVo;
import com.ebc.eservice.vo.card.Message.CardMessageStatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.HyperLogLogOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author: Joey
 * @Description:个人名片 留言 -添加、回复、统计、不同状态查看留言
 * @date:2022/9/24 17:55
 */
@Service
public class PersonCardImp implements PersonCardService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private InteractClientMapper clientMapper;
    @Autowired
    private EbcCardStatMapper ebcCardStatMapper;

    @Autowired
    private CardMessageMapper cardMessageMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private RoleMapper roleMapper;


    @Override
    public JsonResult getPersonCard(Integer staffId) {
        CardInfoVo card = cardMapper.getPersonCard(staffId);
        if(card != null){
            return JsonResult.success(card);
        }
        //code : 2
        return JsonResult.error("获取名片信息失败", null);
    }

    @Override
    public JsonResult getPersonProfile(Integer cardId) {
        //名片的个人简介
        EbcCard card = cardMapper.selectOne(Wrappers.<EbcCard>lambdaQuery()
                .and(wrapper -> wrapper.eq(EbcCard::getId, cardId)));
        String msg = card.getPersonalProfile();
        HashMap<String, Object> map = new HashMap<>();
        if(msg.equals("")){
            return JsonResult.fail("获取失败,没有查到简介信息.");
        }else{
            //获取照片
            byte[] data = null;
            Query query = Query.query(Criteria.where("cardId").is(cardId));
            UploadFile file = mongoTemplate.findOne(query,UploadFile.class);
            map.put("personMsg",msg);
            map.put("pic",file);
        }
        return JsonResult.success(map);
    }


    /********************************* 留言 ******************************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addMessage(CardMessageReqVo mReqVo) {
        JsonResult result=null;
        List<EbcRole> roles = roleMapper.getUserRolesByUid(mReqVo.getUserId());
        if(roles.get(0).getRoleCode().contains("v2")){
            System.out.println("===============留言失败,员工无需留言");
            result = JsonResult.fail("留言发送失败,员工不可给自己留言");
        }else if(roles.get(0).getRoleCode().contains("c1")){
            EbcCardMessage message = new EbcCardMessage();
            message.setCardId(mReqVo.getCardId()).setUserId(mReqVo.getUserId())
                    .setUserName(mReqVo.getUserName())
                    .setCreateId(mReqVo.getUserId())
                    .setContent(mReqVo.getContent())
                    .setOpen(mReqVo.getOpen()).setDel(0).setReplyStatus(0);
            int insert = cardMessageMapper.insert(message);
            if(insert>0){
                addCardMessageStat(mReqVo.getCardId(),mReqVo.getUserId());
                result = JsonResult.success("留言发送成功");
            }
        }else{
            result = JsonResult.fail("留言发送失败");
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult replyMessage(CardMessageRespVo mRespVo) {

        //添加回复
        EbcCardMessage message = new EbcCardMessage();
        message.setCardId(mRespVo.getCardId())
                .setUserName(mRespVo.getReplyName())
                .setUserId(mRespVo.getReplyId())//名片管理员id
                .setCreateId(mRespVo.getReplyId())  //留言回复的回复状态为2 不做查询
                .setContent(mRespVo.getContent()).setReplyStatus(2).setOpen(1).setDel(0);
        cardMessageMapper.insert(message);
        //更新留言id状态 封装方法
        EbcCardMessage message2 = cardMessageMapper.selectOne(Wrappers.<EbcCardMessage>lambdaQuery()
                .and(wrapper -> wrapper.eq(EbcCardMessage::getId, mRespVo.getMessageId())));
        message2.setReplyStatus(1);
        message2.setReplyId(message.getId());//留言id 员工
        int i = cardMessageMapper.updateById(message2);
        if(i>0){
            JsonResult.success("回复成功");
        }
        return JsonResult.fail("回复失败");
    }

    @Override
    public JsonResult getMsgByCardIdUserId(Integer cardId,Integer userId) {

        List<EbcRole> roles = roleMapper.getUserRolesByUid(userId);
        List<CardMessageListVo> messageOpenList = null;
        if(roles.get(0).getRoleCode().contains("v2")){
            messageOpenList = cardMessageMapper.getMsgListStaff(cardId);
        }else if(roles.get(0).getRoleCode().contains("c1")){
           messageOpenList = cardMessageMapper.getMsgList(cardId,userId);
        }else{
            return JsonResult.fail("当前用户未登记");
        }
        //获取留言回复列表 不公开的 用户自己可以看见

        return JsonResult.success(messageOpenList);
    }
    //根据名片id获取所有留言回复列表 用于名片管理
    @Override
    public JsonResult getAllMsgByCardId(Integer cardId) {
        List<CardMessageListVo> messageAllList = cardMessageMapper.getAllMessageList(cardId);
        return JsonResult.success(messageAllList);
    }

    @Override
    public JsonResult getStatMessage(Integer cardId) {
        CardMessageStatVo stat = cardMessageMapper.getMessageStat(cardId);
        return JsonResult.success(stat);
    }

    @Override
    public JsonResult deleteMessage(Integer mid) {
        EbcCardMessage message = cardMessageMapper.selectById(mid);
        Integer replyId = message.getReplyId();
        if(replyId==null){
            cardMessageMapper.deleteById(mid);
        }else{
            cardMessageMapper.deleteById(mid);
            cardMessageMapper.deleteById(replyId);
        }

        return JsonResult.success("删除成功");
    }

    //增加留言统计记录
    public void addCardMessageStat(Integer cardId,Integer userId){
        MyTimeUtil timeUtil = new MyTimeUtil();
        String today = timeUtil.getToDay();
        //名片
        redisTemplate.opsForHash().increment("card:"+cardId+":date:"+today,
                "messageNum", 1);
        // 客户数量记录
        HyperLogLogOperations<String, String> clientVo = redisTemplate.opsForHyperLogLog();
        clientVo.add("cardclient:"+cardId+":date:"+today,"user:"+userId);

        //名片
        QueryWrapper<EbcCardStat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_flag",today);
        queryWrapper.eq("card_id",cardId);
        EbcCardStat cardStat = ebcCardStatMapper.selectOne(queryWrapper);
        if(cardStat != null){//更新
            ebcCardStatMapper.addMessage(today);
        }else{//新增
            System.out.println("员工账号或未登录，留言失败");
//            EbcCardStat stat = new EbcCardStat();
//            stat.setCardId(cardId)
//                    .setMessageNum(1)
//                    .setCreateStatTime(new Date()).setDateFlag(today)
//                    .setDownloadNum(0).setAddContactNum(0)
//                    .setStayTimes(0).setMessageNum(0).setForwardNum(0).setCopyWxAccount(0);
//            ebcCardStatMapper.insert(stat);
        }
        //客户
        QueryWrapper<EbcInteractClient> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("create_inter_time",today);
        queryWrapper2.eq("user_id",userId);
        queryWrapper2.eq("card_id",cardId);
        EbcInteractClient selectClient = clientMapper.selectOne(queryWrapper2);
        if(selectClient == null){//客户第一次访问
            EbcInteractClient client = new EbcInteractClient();
            client.setCardId(cardId).setUserId(userId)
                    .setCreateInterTime(today).setInteractNum(1);
            clientMapper.insert(client);
        }else{ //不为空则更新+1
            clientMapper.updateInteractNum(today,userId);
        }
    }

}
